﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using RegulatoryPlatform.Models;

namespace RegulatoryPlatform.Tools
{
    public class HisHelper
    {
        #region 通用方法
        /// <summary>
        /// 请求HIS预约相关
        /// </summary>
        /// <param name="callName">ESB数据总线接口名</param>
        /// <param name="parmXmlSign">签名</param>
        /// <param name="parmXml">通过ESB访问his方法的入参</param>
        /// <returns></returns>
        private string SetHisBookFyl(string callName, string parmXmlSign, string parmXml)
        {
            string url = "http://101.231.201.106:8193/WebServiceFyl.asmx";
            string parm = string.Format("callName={0}&parmXmlSign={1}&parmXml={2}", callName, parmXmlSign, parmXml);
            return PostXml(url + "/SetHisBookFyl", parm);
        }

        /// <summary>
        /// post提交参数并接受出参
        /// </summary>
        /// <param name="url"></param>
        /// <param name="strPost"></param>
        /// <returns></returns>
        public string PostXml(string url, string strPost)
        {
            string repPara = "";
            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            byte[] byteArray = Encoding.UTF8.GetBytes(strPost);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            try
            {
                WebResponse response = request.GetResponse();
                string statusCode = ((int)((HttpWebResponse)response).StatusCode).ToString();
                string statusDescription = ((HttpWebResponse)response).StatusDescription;
                dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                repPara = HttpUtility.HtmlDecode(reader.ReadToEnd());
            }
            catch (Exception e)
            {
                return e.Message;
            }
            finally
            {
                dataStream.Close();
            }
            return repPara;
        }

        /// <summary>
        /// 请求HIS预约相关
        /// </summary>
        /// <param name="callName">ESB数据总线接口名</param>
        /// <param name="parmXmlSign">签名</param>
        /// <param name="parmXml">通过ESB访问his方法的入参</param>
        /// <returns></returns>
        public string SetHisBookJyl(string callName, string parmXmlSign, string parmXml)
        {
            string url = "http://140.206.83.68:8192/WebServiceJyl.asmx";
            string parm = string.Format("callName={0}&parmXmlSign={1}&parmXml={2}", callName, parmXmlSign, parmXml);
            return PostXml(url + "/SetHisBookJyl", parm);
        }

        /// <summary>
        /// 联众访问his参数设置（属性无CDATA类型）
        /// </summary>
        /// <param name="Param"></param>
        /// <returns></returns>
        private string setXml(Dictionary<string, string> Param)
        {
            string ParamStr = "<?xml version=\"1.0\" encoding=\"gb2312\"?><rows><row";
            foreach (var item in Param)
            {
                ParamStr = ParamStr + " " + item.Key + "=\"" + item.Value + "\"";
            }
            ParamStr = ParamStr + "></row></rows>";
            return ParamStr;
        }

        #endregion

        public List<HospitalGfy> getDocData()
        {
            List<HospitalGfy> ysLis = new List<HospitalGfy>();//医生集合
            List<string> lisExpertid = new List<string>();//同一科室同一级别同一医生不重复添加
            string inXml = "", outXml = "";
            int goNum = 0;
            #region 获取医生
            Dictionary<string, string> param = new Dictionary<string, string>();

            param.Add("hospital", "");//0：汾阳总院；3：浦江分院；2：宝庆分院
            param.Add("partcode", "01,02,11");
            param.Add("stdate", DateTime.Now.ToString("yyyy-MM-dd"));
            param.Add("endate", DateTime.Now.AddDays(15).ToString("yyyy-MM-dd"));
            param.Add("is_simple", "1");
            param.Add("patfrom", "支付宝");
            param.Add("dept_code", "");
            param.Add("platform_code", "8");
            inXml = setXml(param);
            do
            {
                goNum++;
                if (goNum > 1)
                    Thread.Sleep(500);
                //加密入参
                string xorObj = Util.Getxor(DateTime.Now.ToString("yyyy"), "YY01");//异或运算
                string parmXml = inXml + xorObj;
                string sign = Util.GetSHA256Str(parmXml);//加密
                string parmEntity = sign.ToLower();

                //访问HIS接口
                outXml = SetHisBookFyl("YY01", parmEntity, inXml);//从预约项目中帅选医生
            } while (outXml.Contains("retcode=") && goNum < 3);

            XmlDocument xmlRes = new XmlDocument();
            xmlRes.LoadXml(outXml);
            XmlNodeList nodeList = xmlRes.SelectSingleNode("//rows").ChildNodes;
            if (nodeList.Count > 0)
            {
                if (nodeList[0].Attributes["retcode"] == null)
                {
                    foreach (XmlNode node in nodeList)
                    {
                        HospitalGfy gfyYs = new HospitalGfy();//医生
                        gfyYs.hospital = (node.Attributes["deptl2code"].Value).Substring(0, 1);
                        gfyYs.parent_code = (node.Attributes["deptl1code"].Value);
                        gfyYs.partcode = (node.Attributes["partcode"].Value);
                        gfyYs.dept_code = (node.Attributes["deptl2code"].Value);
                        gfyYs.dept_name = (node.Attributes["deptl1name"].Value);
                        gfyYs.expert_id = (node.Attributes["doctorid"].Value);
                        gfyYs.expert_name = (node.Attributes["doctorname"].Value);
                        gfyYs.exptdegree = (node.Attributes["doctordegree"].Value);
                        gfyYs.expert_describe = (node.Attributes["expert_describe"].Value);
                        gfyYs.expert_sort = int.Parse(node.Attributes["expert_sort"].Value);
                        gfyYs.out_date = (node.Attributes["out_date"].Value);
                        gfyYs.grpname = (node.Attributes["grpname"].Value);
                        if (string.IsNullOrWhiteSpace(gfyYs.expert_id.Trim()) || string.IsNullOrWhiteSpace(gfyYs.expert_name.Trim()))
                            continue;
                        string docInfo = gfyYs.hospital + gfyYs.parent_code + node.Attributes["partcode"].Value + gfyYs.expert_id;
                        if (!lisExpertid.Contains(docInfo))
                        {
                            ysLis.Add(gfyYs);
                            lisExpertid.Add(docInfo);
                        }
                    }
                }
            }
            #endregion 获取医生
            #region 获取浦江院区医生
            param.Clear();
            param.Add("hospital", "3");//0：汾阳总院；3：浦江分院；2：宝庆分院
            param.Add("partcode", "01,02,11");
            param.Add("stdate", DateTime.Now.ToString("yyyy-MM-dd"));
            param.Add("endate", DateTime.Now.AddDays(15).ToString("yyyy-MM-dd"));
            param.Add("is_simple", "1");
            param.Add("patfrom", "支付宝");
            param.Add("dept_code", "");
            param.Add("platform_code", "8");
            inXml = setXml(param);
            do
            {
                goNum++;
                if (goNum > 1)
                    Thread.Sleep(500);
                //加密入参
                string xorObj = Util.Getxor(DateTime.Now.ToString("yyyy"), "YY01");//异或运算
                string parmXml = inXml + xorObj;
                string sign = Util.GetSHA256Str(parmXml);//加密
                string parmEntity = sign.ToLower();

                //访问HIS接口
                outXml = SetHisBookJyl("YY01", parmEntity, inXml);//从预约项目中帅选医生
            } while (outXml.Contains("retcode=") && goNum < 3);
            xmlRes = new XmlDocument();
            xmlRes.LoadXml(outXml);
            nodeList = xmlRes.SelectSingleNode("//rows").ChildNodes;
            if (nodeList.Count > 0)
            {
                if (nodeList[0].Attributes["retcode"] == null)
                {
                    foreach (XmlNode node in nodeList)
                    {
                        HospitalGfy gfyYs = new HospitalGfy();//医生
                        gfyYs.hospital = (node.Attributes["deptl2code"].Value).Substring(0, 1);
                        gfyYs.parent_code = (node.Attributes["deptl1code"].Value);
                        gfyYs.partcode = (node.Attributes["partcode"].Value);
                        gfyYs.dept_code = (node.Attributes["deptl2code"].Value);
                        gfyYs.dept_name = (node.Attributes["deptl1name"].Value);
                        gfyYs.expert_id = (node.Attributes["doctorid"].Value);
                        gfyYs.expert_name = (node.Attributes["doctorname"].Value);
                        gfyYs.exptdegree = (node.Attributes["doctordegree"].Value);
                        gfyYs.expert_describe = (node.Attributes["expert_describe"].Value);
                        gfyYs.expert_sort = int.Parse(node.Attributes["expert_sort"].Value);
                        gfyYs.out_date = (node.Attributes["out_date"].Value);
                        gfyYs.grpname = (node.Attributes["grpname"].Value);
                        if (string.IsNullOrWhiteSpace(gfyYs.expert_id.Trim()) || string.IsNullOrWhiteSpace(gfyYs.expert_name.Trim()))
                            continue;
                        string docInfo = gfyYs.hospital + gfyYs.parent_code + (node.Attributes["partcode"].Value) + gfyYs.expert_id;
                        if (!lisExpertid.Contains(docInfo))
                        {
                            ysLis.Add(gfyYs);
                            lisExpertid.Add(docInfo);
                        }
                    }
                }
            }
            #endregion 获取浦江院区医生
            return ysLis;
        }
    }
}